<template>
  <div class="verifyDataList">
    <div style="flex: 1">
      <el-card shadow="never">
        <div slot="header" style="display: flex;align-items: center;justify-content: space-between">
          <n-title title="规则配置"/>
          <div>
            <el-button size="small" plain type="primary" @click="resetFormModel">参数重置</el-button>
            <el-button size="small" plain type="primary" @click="toVerifyWorkIndex">返回核查列表</el-button>
            <el-button size="small" plain type="primary" @click="dialogVisible = true">{{ verifyGradeName }}抽样</el-button>
          </div>
        </div>
        <el-dialog
            title="是否确认核查抽样"
            :visible.sync="dialogVisible"
            width="40%">
          <span>核查抽样只允许抽取一次，核查过程中不能进行数据的编辑、质检、驳回、审核等操作，请确认是否抽样？</span><br>
          <span style="color: red">当前第一阶段规则为{{ruleFormModel.firstRule.ruleType == '1' ? '指定抽取':'按比例抽取'}}</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dataSample" :loading="loading">确 定</el-button>
          </span>
        </el-dialog>
        <div class="rule-title">
          <span>第一阶段规则</span>
        </div>
        <el-tabs v-model="activeFirstRuleType" @tab-click="firstRuleTypeChangeHandle" style="margin-bottom: 10px">
          <el-tab-pane label="指定抽取" name="areaSample">
            <span style="font-size: 14px;margin: 0 10px">请选择一到三个{{ subAreaType }}</span>
            <el-select v-model="ruleFormModel.firstRule.areaCodes" multiple multiple-limit=3 placeholder="请选择">
              <el-option
                  v-for="item in subAreaList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
              </el-option>
            </el-select>
          </el-tab-pane>
          <el-tab-pane label="按比例抽取" name="rateSample">
            <el-table class="custom-row-height" :data="rateSampleTableData" :show-header="false" border>
              <el-table-column align="center" prop="index" width="50"/>
              <el-table-column align="center" prop="content" width="500"/>
              <el-table-column align="center" prop="sampleRate" width="150">
                <template>
                  <el-input v-model="ruleFormModel.firstRule.sampleRate"/>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="remark"/>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div class="rule-title">
          <span>第二阶段规则</span>
        </div>
        <div style="width: 100%">
          <el-table
              ref="multipleTable"
              :data="ruleTableData"
              stripe
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                align="center"
                width="50">
            </el-table-column>
            <el-table-column
                label="序号"
                type="index"
                align="center"
                width="50">
            </el-table-column>
            <el-table-column
                prop="categoryName"
                label="抽样类型"
                align="center"
                width="500">
            </el-table-column>
            <el-table-column
                prop="sampleRate"
                label="抽样比例"
                align="center"
                width="150">
              <template slot-scope="scope">
                <!-- 输入框右侧显示 % 提示 -->
                <div class="input-with-percent">
                  <span class="percent-prefix"> >= </span>
                  <el-input
                      v-model="scope.row.sampleRate"
                      type="number"
                      @input="handleInput(scope.row, 'sampleRate', $event)"
                      @paste.native="(e) => handlePaste(e, scope.row, 'sampleRate')"
                  ></el-input>
                  <span class="percent-suffix">%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                label="备注"
                align="center">
              <template slot-scope="scope">
                <p>点击可修改抽样比例，不低于{{ scope.row.sampleRate }}%</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import DataTable from "@/components/DataTable/DataTable.vue";
import NTitle from "@/components/NTitle.vue";
import {querySampleRuleTemplateList,dataSample} from '@/api/verifyWork';
import {queryUserSubArea} from "@/api/area"
import router from "@/router";
import storeUtils from "@/utils/storeUtils";
import {Message} from "element-ui";

@Component({
  methods: {querySampleRuleTemplateList},
  components: {NTitle, DataTable}
})
export default class sampleRule extends Vue {
  workId: any = router.currentRoute.query.workId;
  verifyTimes: any = router.currentRoute.query.verifyTimes;
  verifyGradeName: any = '市级';
  subAreaType: any = '县';
  activeFirstRuleType: any = "areaSample";
  @Ref("areaTreeSelect") areaTreeSelect!: any
  subAreaList: any = [];
  ruleTemplateData: any = [];
  ruleTableData: any = []
  dialogVisible = false;
  loading = false;
  ruleFormModel: any = {
    workId: router.currentRoute.query.workId,
    firstRule: {
      ruleType:'1',
      areaCodes:[],
      sampleRate:1000
    },
    secondRuleList: [],
  };
  rateSampleTableData:any = [
    {
      index:"01",
      content:"县级调查数据(不含家庭减灾能力)大于1000条的抽样数量",
      sampleRate:100,
      remark:"点击可修改抽样比例，不低于100"
    }
  ]

  //获取登录人的下级区域列表
  getUserAreaInfo() {
    queryUserSubArea().then(res => {
      if (res.data) {
        this.subAreaList = res.data
      }
    })
  }

  //获取二级规则模板数据
  getSecondRuleTemplate() {
    querySampleRuleTemplateList().then(res => {
      if (res.data) {
        this.ruleTableData = res.data.map(item=> ({...item}))
        this.ruleTemplateData = res.data.map(item=> ({...item}))
      }
    })
  }
  //参数重置
  resetFormModel() {
    this.ruleFormModel.firstRule.ruleValue = undefined;
    this.ruleFormModel.firstRule.areaCodes = [];
    this.ruleFormModel.secondRuleList = [];
    console.log(5,this.ruleTemplateData)
    console.log(6,this.ruleTableData)
    this.ruleTableData = this.ruleTemplateData.map(item=> ({...item}));
  }

  //进行数据抽样
  dataSample() {
    if(this.ruleFormModel.firstRule.ruleType == '1') {
      if (this.ruleFormModel.firstRule.areaCodes.length ==0) {
        Message.warning("请选择一到三个"+this.subAreaType);
        return;
      }
    } else {
      if (!this.ruleFormModel.firstRule.sampleRate) {
        Message.warning("请填写抽样比例");
        return;
      }
    }
    this.loading = true
    console.log(3, this.ruleFormModel)
    dataSample(this.ruleFormModel).then(res=> {
      Message.success("数据抽取成功，请返回核查列表查看");
      this.loading = false
      this.dialogVisible = false
    }).catch((err: any) => {
      console.error(err);
      this.loading = false;
    });
    console.log(4)
  }
  //去数据核查首页
  toVerifyWorkIndex() {
    this.$router.push({path: '/verify/verifyWork'});
  }

  //第一阶段规则类型切换
  firstRuleTypeChangeHandle(tab, event) {
    if (tab.name == "areaSample") {
      this.ruleFormModel.firstRule.ruleType = '1'
    } else if(tab.name == "rateSample") {
      this.ruleFormModel.firstRule.ruleType = '2'
    }
  }

  //表格选择
  handleSelectionChange(val) {
    this.ruleFormModel.secondRuleList = val;
  }

  // 展示时拼接 %
  formatPercentage(row, column, cellValue) {
    return `${cellValue}%`;
  }
  // 输入过滤（仅保留数字）
  handleInput(row, key, value) {
    const newValue = value.replace(/[^\d]/g, '');
    if (newValue < 1) {
      row[key] = 1
    } else if(newValue >100) {
      row[key] = 100
    } else {
      row[key] = newValue; // 更新为纯数字
    }
  }
  // 粘贴过滤（同上）
  handlePaste(e, row, key) {
    e.preventDefault();
    const text = e.clipboardData.getData('text/plain');
    const newValue = text.replace(/[^\d]/g, '');
    row[key] = newValue;
  }
  mounted() {
    var dept = storeUtils.getStorageS(storeUtils.CONST.departInfo)
    if(dept) {
      if (dept.areaLevel == '1') {
        this.verifyGradeName = '省级'
        this.subAreaType = '市'
      } else if (dept.areaLevel == '0') {
        this.verifyGradeName = '国家级'
        this.subAreaType = '省'
      }
    }
    this.getUserAreaInfo();
    this.getSecondRuleTemplate();
  }
}
</script>
<style lang="scss" scoped>
.verifyDataList {
  display: flex;
  gap: 10px;
}

.rule-title {
  padding: 5px 0;
  font-size: 17px;
  background-color: #5b9a8e;
  text-align: center;

  span {
    color: white
  }
}
/* 输入框右侧显示 % */
.input-with-percent {
  position: relative;
  display: inline-block;
}
.percent-prefix {
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none; /* 防止遮挡输入框点击 */
  color: #5b9a8e;
}
.percent-suffix {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none; /* 防止遮挡输入框点击 */
  color: #5b9a8e;
}
/* 调整输入框内边距避免文字重叠 */
.el-input__inner {
  padding-right: 25px !important;
}
.el-dialog__title {
  color: #5b9a8e;
  font-weight: bold;
  font-size: 14px;
  padding-bottom: 6px;
  cursor: pointer;
  border-bottom: 2px solid #5b9a8e;
  width: fit-content;
}

.custom-row-height {
  .el-table td,
  .el-table th {
    padding: 8px 0;
  }
  tr{
    line-height: 10px;
  }
}
</style>
